using System;
using System.Diagnostics.Contracts;
using System.Linq;

namespace OpenWaves
{
    public static class EnumExtensions
    {
        public static string GetDisplayText(this Enum value)
        {
            Contract.Requires<ArgumentNullException>(value != null);
            Contract.Ensures(Contract.Result<string>() != null);

            return GetDisplayTextFromAttribute(value) ?? value.ToString();
        }

        private static string GetDisplayTextFromAttribute(Enum value)
        {
            Contract.Requires<ArgumentNullException>(value != null);

            var enumMember = value.GetType().GetMember(value.ToString()).SingleOrDefault();
            if (enumMember == null)
                return null;

            var displayTextProvier = enumMember.GetCustomAttributes(false).OfType<IDisplayTextProvider>().SingleOrDefault();
            if (displayTextProvier == null)
                return null;

            return displayTextProvier.DisplayText;
        }
    }
}